package com.qinglei.recoup.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.hmp.pojo.dto.TMAlarmInfoParam;
import com.qinglei.recoup.hmp.pojo.dto.TMDataItemDTO;
import com.qinglei.recoup.hmp.pojo.dto.TemplateMessageDTO;
import com.qinglei.recoup.system.Template.*;
import com.qinglei.recoup.system.dao.BedHealthDailyStatisticsMapper;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.HealthVO;
import com.qinglei.recoup.system.util.DateTimeUtil;
import com.qinglei.recoup.system.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
@Service
@Slf4j
public class WxService {
    @Value("${wx.appId}")
    private  String APPID ;

    @Value("${wx.appSecret}")
    private  String SECRET;

    @Value("${wx.url}")
    private  String URL;

    private String access_token;
    private Long access_token_updateTime;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BedService bedService;

    @Autowired
    private  BedHealthDailyStatisticsService dailyStatisticsService;

    @Autowired
    private  BedHealthBreathDailyDataService  bedHealthBreathDailyDataService;

    @Autowired
    private BedHealthDailyStatisticsMapper bedHealthDailyStatisticsMapper;

    /**
     * 获取acctoken
     *
     * @return
     */
    private String getAccessToken() {
        if (access_token != null && (access_token_updateTime + 5400000) > new Date().getTime())
            return access_token;
        AccessTokenResult accessTokenResult = restTemplate.getForObject(
                String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                        APPID, SECRET),
                AccessTokenResult.class);
        if (accessTokenResult.getErrcode() == null || accessTokenResult.getErrcode().equals("0")) {
            access_token_updateTime = new Date().getTime();
            access_token = accessTokenResult.getAccess_token();
        } else
            System.out.println("error:" + accessTokenResult);
        return accessTokenResult.getAccess_token();

    }

    /**
     *  * 发送模板消息
     * appId 公众账号的唯一标识
     * appSecret 公众账号的密钥
     * openId 用户标识
     */
    public void send_template_message(String appId, String openId,String snCode,String nickName) {
        Bed bed = bedService.getBedBySn(snCode);

        if(bed==null){
            log.info(snCode+"的设置未绑定床位");
            return;
        }
        LocalDate yesterday = LocalDate.now().plusDays(-1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("bed_id",bed.getId());
        queryWrapper.eq("statistics_date",yesterday.toString());
        BedHealthDailyStatistics  dailyStatistics = dailyStatisticsService.getBaseMapper().selectOne(queryWrapper);
        BedHealthBreathDailyData  bedHealthBreathDailyData = bedHealthBreathDailyDataService.getBaseMapper().selectOne(queryWrapper);
        if(dailyStatistics==null || bedHealthBreathDailyData==null){
            log.info(snCode+"设备昨日未生产报告!");
            return;
        }
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();
        Data_first content = new Data_first();
        content.setValue("您好，"+nickName+"("+bed.getName()+")的健康报告已经生成");
        //content.setColor("#FF0000");
        data.setFirst(content);

        Data_keyword1 keyword1 = new Data_keyword1();
        keyword1.setValue(LocalDate.now().toString());
        //keyword1.setColor("#FF5500");
        data.setKeyword1(keyword1);
        //Integer diagnosisResults = bedHealthBreathDailyData.getDiagnosisResults();
        Double diagnosisResults = bedHealthBreathDailyData.getAhi();
        Integer flagBreathReport = bedHealthBreathDailyData.getFlagBreathReport();
        String  diagnosisResultsStr = null;
//        switch (diagnosisResults){
//            case -1:
//                diagnosisResultsStr = "--";
//                break;
//            case 0:
//                diagnosisResultsStr = "健康";
//                break;
//            case 1:
//                diagnosisResultsStr = "健康";
//                break;
//            case 2:
//                diagnosisResultsStr = "需关注";
//                break;
//            case 3:
//                diagnosisResultsStr = "需关注";
//                break;
//            case 4:
//                diagnosisResultsStr = "需关注";
//                break;
//            default:
//
//        }
        if(bed.getRadarVersion()!=null && "3_0".equals(bed.getRadarVersion())){
            if(0<=diagnosisResults&&5>diagnosisResults)
            {
                diagnosisResultsStr = "健康";
            }else if(0==flagBreathReport&&5<=diagnosisResults){
                diagnosisResultsStr = "需关注";
            }else{
                diagnosisResultsStr = "--";
            }
        }else {
            if (0 == flagBreathReport && 0 <= diagnosisResults && 5 > diagnosisResults) {
                diagnosisResultsStr = "健康";
            } else if (0 == flagBreathReport && 5 <= diagnosisResults) {
                diagnosisResultsStr = "需关注";
            } else {
                diagnosisResultsStr = "--";
            }
        }

        StringBuilder keyword2Str = new StringBuilder("睡眠得分："+dailyStatistics.getScore()+"\n");
        keyword2Str.append("睡眠呼吸："+diagnosisResultsStr);
        Data_keyword2 keyword2 = new Data_keyword2();
        keyword2.setValue(keyword2Str.toString());
        //keyword2.setColor("#FF0000");
        data.setKeyword2(keyword2);

        //备注
        Data_remark remark = new Data_remark();
        remark.setValue("点击可以查看哦~");
        //remark.setColor("#FF0000");
        data.setRemark(remark);

        Integer bedId = bed.getId();

        temp.setTouser(openId);
        temp.setTemplate_id("e0erV-vj73xAcWEsdMRME_zs5ss6WCY0sVqeC3wJvT8");
        temp.setUrl(URL+"/#/pages/healthy/healthy?startDate="+yesterday+"&bedId="+bedId+"&endDate="+yesterday+"&snCode="+snCode+"&type=1&isSubscribe=1&share=true");
        temp.setTopcolor("#173177");
        temp.setData(data);

        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);


    }

    public void sendTemplateMessageFirstDayOfMonth(String appId, String openId,String snCode,String nickName) {
       if(DateTimeUtil.isFirstDayOfMonth(new Date())){
        //if(true){
           Bed bed = bedService.getBedBySn(snCode);
           if(bed==null){
               log.info(snCode+"的设置未绑定床位");
               return;
           }

           Integer bedId = bed.getId();
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
           //获取前一个月第一天
           Calendar calendar1 = Calendar.getInstance();
           calendar1.add(Calendar.MONTH, -1);
           calendar1.set(Calendar.DAY_OF_MONTH,1);
           String firstDay = sdf.format(calendar1.getTime());
           //获取前一个月最后一天
           Calendar calendar2 = Calendar.getInstance();
           calendar2.set(Calendar.DAY_OF_MONTH, 0);
           String lastDay = sdf.format(calendar2.getTime());

           BedHealthQO bedHealthQO = new BedHealthQO();
           bedHealthQO.setBedId(bedId);
           bedHealthQO.setStartDate(LocalDate.parse(firstDay));
           bedHealthQO.setEndDate(LocalDate.parse(lastDay));
           HealthVO healthVO = getHealthVO(bedHealthQO);
           if(healthVO==null){
               return;
           }
            double avgSleepTimes = healthVO.getSleepDuration();
            int sleepHours = (int) (avgSleepTimes /60);
            int sleepMinutes = (int) (avgSleepTimes - sleepHours*60);

           String access_token = getAccessToken();
           String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
           NewOrdersTemplate temp = new NewOrdersTemplate();
           Data data = new Data();
           Data_first content = new Data_first();
           content.setValue("您好，"+nickName+"("+bed.getName()+")上个月的健康报告已经生成");
           //content.setColor("#FF0000");
           data.setFirst(content);

            StringBuilder keyword2Str = new StringBuilder("睡眠平均时长："+sleepHours+"小时"+sleepMinutes+"分钟");
            Data_keyword2 keyword2 = new Data_keyword2();
            keyword2.setValue(keyword2Str.toString());
            data.setKeyword2(keyword2);

           Data_keyword1 keyword1 = new Data_keyword1();
           keyword1.setValue(firstDay+"~"+lastDay);
           //keyword1.setColor("#FF5500");
           data.setKeyword1(keyword1);
            //备注
            Data_remark remark = new Data_remark();
            remark.setValue("点击可以查看哦~");
            //remark.setColor("#FF0000");
            data.setRemark(remark);
           temp.setTouser(openId);
           temp.setTemplate_id("e0erV-vj73xAcWEsdMRME_zs5ss6WCY0sVqeC3wJvT8");
           temp.setUrl(URL+"/#/pages/healthy/healthy?startDate="+firstDay+"&bedId="+bedId+"&endDate="+lastDay+"&snCode="+snCode+"&type=4");
           temp.setTopcolor("#173177");
           temp.setData(data);
           String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
           JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
       }
    }

    public void sendTemplateMessageFirstDayOfWeek(String appId, String openId,String snCode,String nickName) {
        //if(true){
        if(DateTimeUtil.isFirstDayOfWeek(new Date())==1){
            Bed bed = bedService.getBedBySn(snCode);
            if(bed==null){
                log.info(snCode+"的设置未绑定床位");
                return;
            }
        String firstDay = DateTimeUtil.getPreviousMonday();
        String lastDay = DateTimeUtil.getSunday();
        Integer bedId = bed.getId();

        BedHealthQO bedHealthQO = new BedHealthQO();
        bedHealthQO.setBedId(bedId);
        bedHealthQO.setStartDate(LocalDate.parse(firstDay));
        bedHealthQO.setEndDate(LocalDate.parse(lastDay));
        HealthVO healthVO = getHealthVO(bedHealthQO);
        if(healthVO==null){
            return;
        }
        double avgSleepTimes = healthVO.getSleepDuration();
        int sleepHours = (int) (avgSleepTimes /60);
        int sleepMinutes = (int) (avgSleepTimes - sleepHours*60);
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        NewOrdersTemplate temp = new NewOrdersTemplate();
        Data data = new Data();
        Data_first content = new Data_first();
        content.setValue("您好，"+nickName+"("+bed.getName()+")上周的健康报告已经生成");
        data.setFirst(content);

        Data_keyword1 keyword1 = new Data_keyword1();
            keyword1.setValue(firstDay+"~"+lastDay);
        //keyword1.setColor("#FF5500");
        data.setKeyword1(keyword1);

        StringBuilder keyword2Str = new StringBuilder("睡眠平均时长："+sleepHours+"小时"+sleepMinutes+"分钟");
        Data_keyword2 keyword2 = new Data_keyword2();
        keyword2.setValue(keyword2Str.toString());
        data.setKeyword2(keyword2);

        //备注
        Data_remark remark = new Data_remark();
        remark.setValue("点击可以查看哦~");
        //remark.setColor("#FF0000");
        data.setRemark(remark);
        temp.setTouser(openId);
        temp.setTemplate_id("e0erV-vj73xAcWEsdMRME_zs5ss6WCY0sVqeC3wJvT8");
        temp.setUrl(URL+"/#/pages/healthy/healthy?startDate="+firstDay+"&bedId="+bedId+"&endDate="+lastDay+"&snCode="+snCode+"&type=3");
        temp.setTopcolor("#173177");
        temp.setData(data);
        String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day");
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
        }
    }


    public HealthVO getHealthVO(BedHealthQO bedHealthQO){
        HealthVO health = bedHealthDailyStatisticsMapper.selectBedHealth(bedHealthQO);

//        QueryWrapper QueryWrapperDaySum = new QueryWrapper();
//        QueryWrapperDaySum.eq("bed_id",bedHealthQO.getBedId());
//        QueryWrapperDaySum.eq("result_flag",0);
//        QueryWrapperDaySum.between("statistics_date",bedHealthQO.getStartDate(),bedHealthQO.getEndDate());
//        Integer daySum = bedHealthDailyStatisticsMapper.selectCount(QueryWrapperDaySum);
//
//        Integer scoreSum = bedHealthDailyStatisticsMapper.getSumScore(bedHealthQO);


        return health;
    }

    public void sendAlarmTemplateMessage(TMAlarmInfoParam tmAlarmInfoParam) {
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        TemplateMessageDTO templateDTO = new TemplateMessageDTO();
        templateDTO.setTouser("openId");
        templateDTO.setTemplate_id("U05CfE9e55dQZHZvIqosx_GnFPny7O02RbOGI7duXPQ");
//        templateDTO.setUrl(URL);
        Map<String, TMDataItemDTO> data = new HashMap<>();
        TMDataItemDTO first = new TMDataItemDTO();
        first.setValue("您关注的设备刚刚发生了一次报警");
        data.put("first", first);

        TMDataItemDTO keyword1 = new TMDataItemDTO();
        keyword1.setValue("报警内容");
        data.put("keyword1", keyword1);

        TMDataItemDTO keyword2 = new TMDataItemDTO();
        keyword2.setValue("区域位置");
        data.put("keyword2", keyword2);

        TMDataItemDTO keyword3 = new TMDataItemDTO();
        keyword3.setValue("报警时间");
        data.put("keyword3", keyword3);

        TMDataItemDTO remark = new TMDataItemDTO();
        remark.setValue("请您及时关注");
        data.put("remark", remark);

        templateDTO.setData(data);
        String bodyStr = JsonUtils.objectToJson(templateDTO);
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", bodyStr);
        System.out.println(jsonObject);
    }
}
